#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/7/9 11:20
# @Author  : Tom_zc
# @FileName: clear_file_to_obs.py.py
# @Software: PyCharm

import sys
import click
import logging
from pathlib import Path
from datetime import datetime, timedelta

CURR_DIR = Path(__file__).resolve()
ROOT_DIR = CURR_DIR.parent.parent.parent
sys.path.append(ROOT_DIR.as_posix())
from scripts.utils.obs_helper import ObsHelper

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class PipeLineLogHelper:

    def __init__(self, ak, sk, obs_endpoint):
        self._obs_helper = ObsHelper(ak, sk, obs_endpoint)

    def clear(self, bucket_name, prefix, days):
        before_current_time = (datetime.now() - timedelta(days=int(days))).strftime('%Y/%m/%d %H:%M:%S')
        file_infos = self._obs_helper.list_objects(bucket_name, prefix)
        for file_info in file_infos:
            if file_info.lastModified < before_current_time:
                logging.info("file:{} must be delete, and time:{}".format(file_info, file_info.lastModified))
                ret = self._obs_helper.delete_object(bucket_name, file_info)
                logging.info("delete the file {}, and result:{}".format(file_info, ret))


@click.command()
@click.option("--ak")
@click.option("--sk")
@click.option("--obs_endpoint")
@click.option("--obs_bucket_name")
@click.option("--prefix")
@click.option("--days")
def main(ak, sk, obs_endpoint, obs_bucket_name, prefix, days):
    logging.info("=" * 20 + "start to clear the file in obs" + "=" * 20)

    if not all([ak, sk, obs_endpoint, obs_bucket_name]):
        logging.info("Lack of params, Please check.")
        sys.exit(-1)

    pipeline_log_helper = PipeLineLogHelper(ak, sk, obs_endpoint)

    pipeline_log_helper.clear(obs_bucket_name, prefix, days)

    logging.info("=" * 20 + "clear the file in obs" + "=" * 20)


if __name__ == '__main__':
    main()
